package com.myapp.ruyixing.ui;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.myapp.ruyixing.R;
import com.myapp.ruyixing.http.RYHttpClient;
import com.myapp.ruyixing.http.RYHttpResponseHandler;
import com.myapp.ruyixing.model.CardBalance;
import com.myapp.ruyixing.ui.widget.TitleBar;
import com.myapp.ruyixing.utils.LoginHelper;

public class CardBalanceActivity extends Activity {

	RYHttpResponseHandler mHttpResponseHandler = new RYHttpResponseHandler() {

		@Override
		public void onSuccess(Object o) {
			try {
				CardBalance balance = (CardBalance) o;
				onLoadingDataFinished(true, balance);
			} catch (Exception e) {
				onFailure(null);
			}
		}

		@Override
		public void onFailure(Throwable throwable) {
			onLoadingDataFinished(false, null);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_card_balance);
		((TitleBar) findViewById(R.id.title_bar))
				.setOnIconClickedListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						onBackPressed();
					}
				});
		String nickname = LoginHelper.getInstance().getNickName();
		if (!TextUtils.isEmpty(nickname)) {
			((TextView) findViewById(R.id.user_nickname)).setText(nickname);
		}

		onLoadingDataStarted(LoginHelper.getInstance().getBDUSS());
	}

	private void onLoadingDataStarted(String bduss) {
		((TitleBar) findViewById(R.id.title_bar)).showLoading(true);
		RYHttpClient.getCardBalance(this, mHttpResponseHandler, bduss);
	}

	private void showToast(String msg) {
		Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
	}

	private void onLoadingDataFinished(boolean succeed, CardBalance balance) {
		((TitleBar) findViewById(R.id.title_bar)).showLoading(false);
		if (succeed && balance != null && !TextUtils.isEmpty(balance.balance)) {
			String b = getString(R.string.ruyixing_card_balance_money)
					+ balance.balance;
			((TextView) findViewById(R.id.text_balance)).setText(b);
		} else {
			showToast("加载余额失败！");
		}
	}

}
